def hamming_dist(hash1, hash2, hash_bits):
    x = (hash1 ^ hash2) & ((1 << hash_bits) - 1)
    tot = 0
    while x:
        tot += 1
        x &= x - 1
    return tot


def similarity(hash1, hash2):
    a = float(hash1)
    b = float(hash2)
    if a > b:
        return b / a
    else:
        return a / b


def float_hash(source, hash_bits):
    if not source:
        return 0
    else:
        x = (int(source[0] * 100)) << 7
        # m = 1000003
        # mask = 2 ** hash_bits - 1
        # for c in source:
        #     x = ((x * m) ^ ord(c)) & mask
        # x ^= len(source)
        if x == -1:
            x = -2
        return x


def get_hash(tokens, hash_bits=128):
    v = [0] * hash_bits
    for t in [float_hash(x, hash_bits) for x in tokens]:  # t为token的普通hash值
        for i in range(hash_bits):
            bit_mask = 1 << i
            if t & bit_mask:
                v[i] += 1  # 查看当前bit位是否为1,是的话将该位+1
            else:
                v[i] -= 1  # 否则的话,该位-1
    fingerprint = 0
    for i in range(hash_bits):
        if v[i] >= 0:
            fingerprint += 1 << i
    return fingerprint  # 整个文档的fingerprint为最终各个位>=0的和


